package com.shadow.shadowhost

import android.app.Activity
import android.content.Context
import android.os.Bundle
import android.view.View
import android.widget.Button
import android.widget.LinearLayout
import android.widget.TextView
import com.tencent.shadow.dynamic.host.EnterCallback
import com.tencent.shadow.sample.introduce_shadow_lib.InitApplication
import com.tencent.shadow.sample.introduce_shadow_lib.PmUpdater


class MainActivity : Activity() {
    fun getContext():Context {
        return this
    }
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        val linearLayout = LinearLayout(this)
        linearLayout.orientation = LinearLayout.VERTICAL
        val textView = TextView(this)
        textView.text = "宿主App"
        val button = Button(this)
        button.text = "启动插件"
        button.setOnClickListener { v ->
            v.isEnabled = false //防止点击重入
            val bundle = Bundle()
            bundle.putString(KEY_PLUGIN_ZIP_PATH, PmUpdater.getPluginFile(getContext()).absolutePath)
            bundle.putString(KEY_PLUGIN_PART_KEY, "pp")
            bundle.putString(KEY_ACTIVITY_CLASSNAME, "com.shadow.plugin_app.MainActivity")
            val pluginManager = InitApplication.getPluginManager()
            pluginManager.enter(
                this@MainActivity,
                FROM_ID_START_ACTIVITY.toLong(),
                bundle,
                object : EnterCallback {
                    override fun onShowLoadingView(view: View) {
                        this@MainActivity.setContentView(view) //显示Manager传来的Loading页面
                    }

                    override fun onCloseLoadingView() {
                        this@MainActivity.setContentView(linearLayout)
                    }

                    override fun onEnterComplete() {
                        v.isEnabled = true
                    }
                })
        }
        linearLayout.addView(textView)
        linearLayout.addView(button)
        val callServiceButton = Button(this)
        callServiceButton.text = "调用插件Service，结果打印到Log"
        callServiceButton.setOnClickListener { v ->
            v.isEnabled = false //防止点击重入
            val pluginManager = InitApplication.getPluginManager()
            pluginManager.enter(
                this@MainActivity,
                FROM_ID_CALL_SERVICE.toLong(),
                null,
                null
            )
        }
        linearLayout.addView(callServiceButton)
        setContentView(linearLayout)
    }

    companion object {
        const val FROM_ID_START_ACTIVITY = 1001
        const val FROM_ID_CALL_SERVICE = 1002

        const val KEY_PLUGIN_ZIP_PATH = "pluginZipPath"
        const val KEY_ACTIVITY_CLASSNAME = "KEY_ACTIVITY_CLASSNAME"
        const val KEY_EXTRAS = "KEY_EXTRAS"
        const val KEY_PLUGIN_PART_KEY = "KEY_PLUGIN_PART_KEY"
    }
}